# -*- coding:utf-8 -*-
"""
@author:Mr.头发又黑又长
@file: Myauthenticator.py
@time: 2020/05/11
"""
from itsdangerous import SignatureExpired, BadSignature
from rest_framework import authentication
from rest_framework.exceptions import AuthenticationFailed

from apps.user.util import token_confirm
from common.response_code import RET, error_map
from db.models import XlzUser


class UserAuthenticator(authentication.BaseAuthentication):

    def authenticate(self, request):
        token = request.headers.get("token", None)

        if not token:
            raise AuthenticationFailed({"msg": RET.NOT_TOKEN, "code": error_map[RET.NOT_TOKEN]})

        try:
            user_id = token_confirm.confirm_validate_token(token)
        except SignatureExpired as E:
            raise AuthenticationFailed({"msg": RET.TOKEN_FAILUER, "code": error_map[RET.TOKEN_FAILUER]})
        except BadSignature:
            raise AuthenticationFailed({"msg": RET.TOKEN_ERROR, "code": error_map[RET.TOKEN_ERROR]})
        except Exception:
            raise AuthenticationFailed({"msg": RET.UNKOWNERR, "code": error_map[RET.UNKOWNERR]})
        try:
            user = XlzUser.objects.get(pk=int(user_id))
        except Exception as E:
            raise AuthenticationFailed({"msg": RET.UNKOWNERR, "code": error_map[RET.UNKOWNERR]})
        return user, True  # 返回 user, auth
